package delay.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.CustomExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * https://github.com/rabbitmq/rabbitmq-delayed-message-exchange (有此插件使用说明）
 * This plugin adds delayed-messaging (or scheduled-messaging) to RabbitMQ.
 *
 * A user can declare an exchange with the type x-delayed-message
 * and then publish messages with the custom header x-delay
 * expressing in milliseconds a delay time for the message.
 * The message will be delivered to the respective queues after x-delay milliseconds.
 */
@Configuration
public class DelayConfiguration {
    public static final String DELAY_EXCHANGE_NAME = "delay_ex";
    public static final String DELAY_QUEUE_NAME = "delay_queue";
    public static final String DELAY_ROUTING_NAME = "delay_routing";

    @Bean
    public CustomExchange delayExchange(){
        Map<String, Object> params = new HashMap<>();
        //这个参数是必须指定的，不能省略，就是说明延迟交换机的路由行为采用哪种类型交换机的路由行为
        //可以指定direct，topic等，值必须是一个存在的交换机类型
        params.put("x-delayed-type", "direct");
        /**
         * 第二个参数一定不要配错,指定的是交换机的类型，与延迟插件是配套的
         */
        return new CustomExchange(DELAY_EXCHANGE_NAME, "x-delayed-message", true, false, params);
    }

    @Bean
    public Queue delayQueue(){
        return new Queue(DELAY_QUEUE_NAME, true);
    }

    @Bean
    public Binding delayBinding(){
        return BindingBuilder
                .bind(delayQueue())
                .to(delayExchange())
                .with(DELAY_ROUTING_NAME)
                .noargs();
    }

    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }
}
